package com.example.fruitdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.fruitdemo.pojo.User;
import com.example.fruitdemo.ruslet.R;
import com.example.fruitdemo.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
   private  UserService userService;
    @GetMapping("/page")
    public R<Page> userpage(int page,int pageSize){
        Page pageinfo=new Page(page,pageSize);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(User::getCreatetime);
        userService.page(pageinfo,queryWrapper);
        log.info("结果是", new Page[]{pageinfo});
        return R.Ok(pageinfo);
    }

    //返回用户信息
    @GetMapping("/getuser")
    public R<User> getuser(String authorization){
        return userService.getUser(authorization);
    }
    //编辑用户信息
    @PostMapping("/setuser")
    public R<Object> setuser(@Validated @RequestBody User user, BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach(item -> {
                String msg = item.getDefaultMessage();
                String field = item.getField();
                map.put(field, msg);
            });
            //System.out.println(map);
            Object err = JSONObject.toJSON(map);
            return R.Err(err);
        }
        return userService.setuser(user);
    }

}
